#include <stdint-gcc.h>
#include "uart.h"

// -1 : aborted
//  0 : EOT received
//  1 : packet received
int xmodem_recv_packet(int pktno, uint8_t packet[128])
{
	uint8_t recv;
	uint8_t cksum;
	uint8_t pktno8;
	int i;

restart:
	recv = uart_in(); // SOH or EOT
	if (recv == 4) {
		uart_out(6); // ACK
		return 0;
	}
	if (recv != 1) {
abort:
		uart_out(24);
		return -1;
	}
	recv = uart_in(); // packet number
	pktno8 = pktno;
	if (recv != pktno8) {
		goto abort;
	}
	recv = uart_in(); // 1's complement of packet number
	if ((recv^pktno8) != 255) {
		goto abort;
	}

	cksum = 0;
	for (i=0; i<128; i++) {
		recv = uart_in();
		packet[i] = recv;
		cksum += recv;
	}

	recv = uart_in(); // checksum
	if (recv == cksum) {
		uart_out(6); // ACK
		return 1;
	}

	uart_out(21); // NAK

	goto restart;
}
